export function changeTableStyle() {
    // 创建样式内容
    const isTruncation = (localStorage.getItem('tableDisplay') || 'Truncation') === 'Truncation';

    const truncationStyles = `
        overflow: hidden !important;
        text-overflow: ellipsis !important;
        white-space: nowrap !important;
        display: block !important;
        width: 100% !important;
        min-width: initial !important;
    `;

    const normalStyles = `
        white-space: normal !important;
        word-wrap: break-word !important;
        word-break: normal !important;
        height: initial !important;
        min-width: initial !important;
        line-height: 1.4 !important;
    `;

    const selector = `.el-table:not(.table-blacklist) .el-table__body-wrapper .el-table__row .el-table__cell .cell`;
    const Blacklist = `.table-blacklist, .el-checkbox, .el-switch, .el-tag, .el-icon`;

    const styleContent = `
        ${selector}:not(:has(${Blacklist})),
        ${selector}:not(:has(${Blacklist})) .pre-text,
        ${selector}:not(:has(${Blacklist})) div:last-child:not(:has(div)),
        ${selector}:not(:has(${Blacklist})) a,
        .table-whitelist:not(:has(.table-blacklist)) {
            ${isTruncation ? truncationStyles : normalStyles}
        }
        ${selector}:not(:has(${Blacklist})) {
            ${isTruncation ? '' : 'padding: 8px 12px !important;'}
        }
    `;

    // 检查是否存在 id 为 'custom-table-style' 的 style 元素
    let styleElement = document.getElementById('custom-table-style');

    if (styleElement) {
        // 如果存在，修改其内容
        styleElement.textContent = styleContent;
    } else {
        // 如果不存在，创建并插入新的 style 元素
        styleElement = document.createElement('style');
        styleElement.id = 'custom-table-style';
        styleElement.textContent = styleContent;
        document.head.appendChild(styleElement);
    }

    document.querySelectorAll('.el-table').forEach((table) => {
        // 确保 table 是 Vue 组件实例
        const vueComponent = table.__vue__;
        if (vueComponent && typeof vueComponent.doLayout === 'function') {
          vueComponent.doLayout();
        }
    });      
}

export function setupMessageListener() {
    // 监听来自父页面的消息
    window.addEventListener('message', event => {
        // 不接收其他域名发送的信息
        if (
            process.env.NODE_ENV === 'production'
            && event.origin !== window.location.origin
        )
            return;
        if (event.data.action === 'changeTableStyle') {
            changeTableStyle();
        }
    });
}